<template>
  <div class="label-maker">
    <div class="page-header">
      <h2>标签制作</h2>
      <div class="header-actions">
        <el-button type="info" @click="clearForm">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        <el-button type="primary" @click="createLabel" :loading="creating">
          <el-icon><Printer /></el-icon>
          制作
        </el-button>
      </div>
    </div>

    <!-- 标签预览和表单 -->
    <el-row :gutter="30">
      <!-- 左侧：表单输入 -->
      <el-col :span="12">
        <el-card class="form-card">
          <template #header>
            <span>标签信息填写</span>
          </template>

          <el-form
            :model="labelForm"
            :rules="rules"
            ref="labelFormRef"
            label-width="100px"
            size="large">

            <el-form-item label="订单编号" prop="orderNumber">
              <el-input
                v-model="labelForm.orderNumber"
                placeholder="请输入订单编号"
                clearable/>
            </el-form-item>

            <el-form-item label="物料编码" prop="materialCode">
              <el-input
                v-model="labelForm.materialCode"
                placeholder="请输入物料编码"
                clearable/>
            </el-form-item>

            <el-form-item label="客户型号" prop="customerModel">
              <el-input
                v-model="labelForm.customerModel"
                placeholder="请输入客户型号"
                clearable/>
            </el-form-item>

            <el-form-item label="生产编码" prop="productionCode">
              <el-input
                v-model="labelForm.productionCode"
                placeholder="请输入生产编码"
                clearable/>
            </el-form-item>

            <el-form-item label="数量" prop="quantity">
              <el-input
                v-model="labelForm.quantity"
                placeholder="请输入数量（如：1000）"
                clearable>
                <template #append>pcs</template>
              </el-input>
            </el-form-item>

            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker
                v-model="labelForm.productionDate"
                type="date"
                placeholder="选择生产日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：标签预览 -->
      <el-col :span="12">
        <el-card class="preview-card">
          <template #header>
            <span>标签预览</span>
          </template>

          <div class="label-preview">
            <div class="label-card">
              <div class="label-header">
                <h3>印制电路板</h3>
                <div class="corner-decoration corner-tl"></div>
                <div class="corner-decoration corner-tr"></div>
                <div class="corner-decoration corner-bl"></div>
                <div class="corner-decoration corner-br"></div>
              </div>

              <div class="label-content">
                <div class="info-row">
                  <div class="info-label">订单编号：</div>
                  <div class="info-value">{{ labelForm.orderNumber || '-' }}</div>
                </div>

                <div class="info-row">
                  <div class="info-label">物料编码：</div>
                  <div class="info-value">{{ labelForm.materialCode || '-' }}</div>
                </div>

                <div class="info-row">
                  <div class="info-label">客户型号：</div>
                  <div class="info-value">{{ labelForm.customerModel || '-' }}</div>
                </div>

                <div class="info-row">
                  <div class="info-label">生产编码：</div>
                  <div class="info-value">{{ labelForm.productionCode || '-' }}</div>
                </div>

                <div class="info-row">
                  <div class="info-label">数量：</div>
                  <div class="info-value highlight">{{ labelForm.quantity ? labelForm.quantity + ' pcs' : '-' }}</div>
                </div>

                <div class="info-row">
                  <div class="info-label">生产日期：</div>
                  <div class="info-value">{{ labelForm.productionDate || '-' }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 说明信息 -->
<!--    <el-card class="help-card">-->
<!--      <template #header>-->
<!--        <span>使用说明</span>-->
<!--      </template>-->
<!--      <el-row :gutter="30">-->
<!--        <el-col :span="8">-->
<!--          <h4>填写要求：</h4>-->
<!--          <ul>-->
<!--            <li>所有字段都必须填写</li>-->
<!--            <li>订单编号请使用标准格式</li>-->
<!--            <li>数量只需填写数字部分</li>-->
<!--            <li>生产日期请选择正确日期</li>-->
<!--          </ul>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <h4>操作步骤：</h4>-->
<!--          <ol>-->
<!--            <li>填写左侧表单的所有字段</li>-->
<!--            <li>右侧预览区域实时显示效果</li>-->
<!--            <li>确认无误后点击"制作"按钮</li>-->
<!--            <li>系统将自动下载PDF标签</li>-->
<!--          </ol>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <h4>注意事项：</h4>-->
<!--          <ul>-->
<!--            <li>生成的PDF适合A4纸张打印</li>-->
<!--            <li>建议使用激光打印机</li>-->
<!--            <li>标签内容请仔细核对</li>-->
<!--            <li>如需重新制作请点击"清空"</li>-->
<!--          </ul>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--    </el-card>-->
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Printer } from '@element-plus/icons-vue'
import { createLabel as createLabelApi } from '@/api/label'

export default {
  name: 'LabelMaker',
  components: {
    Delete,
    Printer
  },
  setup() {
    const creating = ref(false)
    const labelFormRef = ref(null)

    // 表单数据
    const labelForm = reactive({
      orderNumber: '',
      materialCode: '',
      customerModel: '',
      productionCode: '',
      quantity: '',
      productionDate: ''
    })

    // 表单验证规则
    const rules = {
      orderNumber: [
        { required: true, message: '请输入订单编号', trigger: 'blur' }
      ],
      materialCode: [
        { required: true, message: '请输入物料编码', trigger: 'blur' }
      ],
      customerModel: [
        { required: true, message: '请输入客户型号', trigger: 'blur' }
      ],
      productionCode: [
        { required: true, message: '请输入生产编码', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { pattern: /^\d+$/, message: '数量必须是正整数', trigger: 'blur' }
      ],
      productionDate: [
        { required: true, message: '请选择生产日期', trigger: 'change' }
      ]
    }

    // 清空表单
    const clearForm = () => {
      Object.assign(labelForm, {
        orderNumber: '',
        materialCode: '',
        customerModel: '',
        productionCode: '',
        quantity: '',
        productionDate: ''
      })

      if (labelFormRef.value) {
        labelFormRef.value.clearValidate()
      }

      ElMessage.success('表单已清空')
    }

    // 制作标签
    const createLabel = async () => {
      if (!labelFormRef.value) return

      try {
        await labelFormRef.value.validate()

        creating.value = true

                // 调用后端API
        const response = await createLabelApi(labelForm)
        
        console.log('API响应:', response)
        console.log('响应类型:', typeof response)
        console.log('响应是否为Blob:', response instanceof Blob)
        
        if (response) {
          // 检查响应是否为有效的PDF数据
          if (response instanceof Blob && response.size > 0) {
            // 创建下载链接
            const blob = new Blob([response], { type: 'application/pdf' })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            
            // 生成文件名 (与后端保持一致)
            const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '_')
            link.download = `Label_${labelForm.orderNumber.replace(/[^a-zA-Z0-9]/g, '_')}_${timestamp}.pdf`
            
            document.body.appendChild(link)
            link.click()
            
            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
            
            ElMessage.success('标签制作成功，文件已下载')
          } else {
            console.error('响应数据无效:', response)
            ElMessage.error('服务器返回的PDF数据无效')
          }
        } else {
          ElMessage.error('服务器未返回数据')
        }
      } catch (error) {
        console.error('制作标签失败:', error)
        console.error('错误详情:', {
          message: error.message,
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })
        
        let errorMessage = '制作标签失败'
        if (error.response) {
          errorMessage += `：${error.response.status} ${error.response.statusText}`
        } else if (error.message) {
          errorMessage += `：${error.message}`
        }
        
        ElMessage.error(errorMessage)
      } finally {
        creating.value = false
      }
    }

    return {
      creating,
      labelFormRef,
      labelForm,
      rules,
      clearForm,
      createLabel
    }
  }
}
</script>

<style scoped>
.label-maker {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-card {
  height: 600px;
}

.preview-card {
  height: 600px;
}

.help-card {
  margin-top: 20px;
}

.label-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  background: #f5f7fa;
  border-radius: 8px;
}

.label-card {
  background: white;
  border: 2px solid #000;
  border-radius: 4px;
  width: 150px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.label-header {
  background: #2c3e50;
  color: white;
  padding: 6px;
  text-align: center;
  position: relative;
}

.label-header h3 {
  font-size: 12px;
  letter-spacing: 1px;
  font-weight: bold;
  margin: 0;
}

.label-content {
  padding: 8px 10px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 3px 0;
  border-bottom: 1px solid #e0e0e0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: bold;
  color: #333;
  font-size: 8px;
  flex: 0 0 35%;
}

.info-value {
  color: #000;
  font-size: 8px;
  flex: 1;
  text-align: left;
  padding-left: 4px;
}

.highlight {
  color: #e63946 !important;
  font-weight: bold;
}

.corner-decoration {
  position: absolute;
  width: 6px;
  height: 6px;
}

.corner-tl {
  top: 3px;
  left: 3px;
  border-top: 1px solid #adb5bd;
  border-left: 1px solid #adb5bd;
}

.corner-tr {
  top: 3px;
  right: 3px;
  border-top: 1px solid #adb5bd;
  border-right: 1px solid #adb5bd;
}

.corner-bl {
  bottom: 3px;
  left: 3px;
  border-bottom: 1px solid #adb5bd;
  border-left: 1px solid #adb5bd;
}

.corner-br {
  bottom: 3px;
  right: 3px;
  border-bottom: 1px solid #adb5bd;
  border-right: 1px solid #adb5bd;
}

.help-card h4 {
  color: #409eff;
  margin-bottom: 10px;
}

.help-card ul,
.help-card ol {
  padding-left: 20px;
  line-height: 1.8;
}

.help-card li {
  margin-bottom: 5px;
  color: #606266;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-card__header) {
  font-weight: bold;
  color: #303133;
}
</style>
